package com.prevpn.api;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.prevpn.common.CommonResponse;
import com.prevpn.common.CommonUtil;
import com.prevpn.common.GroupResponse;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CreateLocalUser {

    //public GroupResponse queryGroupByPath(String groupPath) {
    //    //String path = "/api/v3/group/queryByFullPath";
    //    String path = "/api/v1/localUserGroup/queryGroupByPath";
    //    Map<String, Object> params = new HashMap<>();
    //    params.put("path", groupPath);
    //
    //    String response = CommonUtil.openApiGetRequest(path, params);
    //    System.out.println(response);
    //
    //    CommonResponse<GroupResponse> commonResponse = JSONUtil.toBean(response, new TypeReference<CommonResponse<GroupResponse>>() {
    //    }, false);
    //
    //    return commonResponse.getData();
    //}

    //public List<String> createLocalUser() {
    //    GroupResponse groupResponse = queryGroupByPath("/");
    //    if (StrUtil.isEmpty(groupResponse.getId())) {
    //        System.out.println("查询不到当前用户目录，请检查GroupPath");
    //        return null;
    //    }
    //
    //    String path = "/api/v2/localUser/createUser";
    //    //String path = "/api/v3/user/create";
    //    String password = "user@1234";
    //    LocalUserVo localUserVo = new LocalUserVo();
    //    localUserVo.setName("lisi");
    //    localUserVo.setPassword(CommonUtil.encrypt(password));
    //    localUserVo.setPwdModel("rsa");
    //    localUserVo.setPhone("13800000001");
    //    localUserVo.setGroupId(groupResponse.getId());
	//	/*
	//	{
	//		"userDirectoryId": "1",
	//		"showAll": 0,
	//		"path": "/",
	//		"include": {
	//			"user": {
	//				"pageSize": 20,
	//				"pageIndex": 1
	//			}
	//		}
	//	}
	//	如果是上面这种格式的请求体，可以采用下面的方式构造，注意需要pom.xml指定5.8.26及以上版本的hutool-all包
    //    HashMap<String,Object> node = new HashMap<String,Object>();
    //    node.put("userDirectoryId","1");
    //    node.put("showAll",0);
    //    node.put("path","/");
    //    HashMap<String,Object> include = new HashMap<String,Object>();
    //    node.put("include",include);
    //    HashMap<String,Object> user = new HashMap<String,Object>();
    //    user.put("pageSize",20);
    //    user.put("pageIndex",1);
    //    include.put("user",user);
    //    System.out.println(JSONUtil.toJsonStr(node));
	//	*/
    //    String response = CommonUtil.openApiPostRequest(path, JSONUtil.toJsonStr(localUserVo));
    //    CommonResponse<List<String>> commonResponse = JSONUtil.toBean(response, new TypeReference<CommonResponse<List<String>>>() {
    //    }, false);
    //
    //    if (!StrUtil.equals(commonResponse.getMsg(), "200")) {
    //        System.out.println(commonResponse.getMsg());
    //        return null;
    //    }
    //    return commonResponse.getData();
    //}

    /**
     * 通过完整路径查询组织架构信息
     * @param directoryDomain 用户目录唯一标识（例如 local）
     * @param fullPath 组织架构完整路径（例如 "/" 或 "/客服体系/专家中心"）
     * @return 组织架构信息
     */
    public GroupResponse queryGroupByPath(String directoryDomain, String fullPath) {
        String path = "/api/v3/group/queryByFullPath";
        Map<String, Object> params = new HashMap<>();
        params.put("directoryDomain", directoryDomain);
        params.put("fullPath", fullPath);

        String response = CommonUtil.openApiGetRequest(path, params);
        System.out.println("组织架构查询响应：" + response);

        CommonResponse<GroupResponse> commonResponse = JSONUtil.toBean(
                response, new TypeReference<CommonResponse<GroupResponse>>() {}, false);

        return commonResponse.getData();
    }

    /**
     * 创建本地用户（v3接口）
     */
    public List<String> createLocalUser() {
        // 1️⃣ 查询组织信息（根路径 /）
        GroupResponse groupResponse = queryGroupByPath("local", "/");
        if (groupResponse == null || StrUtil.isEmpty(groupResponse.getId())) {
            System.out.println("❌ 查询不到当前组织，请检查 GroupPath");
            return null;
        }

        // 2️⃣ 目标接口路径
        String path = "/api/v3/user/create";

        // 3️⃣ 构造请求体
        String password = "user@1234";
        Map<String, Object> body = new HashMap<>();
        body.put("directoryDomain", "local");         // 本地目录
        body.put("name", "lisi");                     // 用户名
        body.put("displayName", "lisi");              // 显示名
        body.put("password", CommonUtil.encrypt(password)); // 加密密码
        body.put("pwdModel", "rsa");                  // 密码加密模式

        // 组织架构对象（必须）
        Map<String, Object> groupObj = new HashMap<>();
        groupObj.put("key", "id");
        groupObj.put("data", groupResponse.getId());
        body.put("group", groupObj);

        // 可选字段
        body.put("phone", "13800000001");
        body.put("email", "lisi@example.com");
        body.put("description", "通过OpenAPI创建的本地用户");

        // 4️⃣ 调用 POST 请求
        String response = CommonUtil.openApiPostRequest(path, JSONUtil.toJsonStr(body));
        System.out.println("创建用户响应：" + response);

        // 5️⃣ 解析响应结果
        CommonResponse<List<String>> commonResponse = JSONUtil.toBean(
                response, new TypeReference<CommonResponse<List<String>>>() {}, false);

        if (commonResponse == null || !"OK".equalsIgnoreCase(commonResponse.getCode())) {
            System.out.println("❌ 创建用户失败：" + (commonResponse != null ? commonResponse.getMsg() : "无响应"));
            return null;
        }

        System.out.println("✅ 用户创建成功，ID：" + commonResponse.getData());
        return commonResponse.getData();
    }

    // 测试入口
    public static void main(String[] args) {
        CreateLocalUser api = new CreateLocalUser();
        api.createLocalUser();
    }
}
